﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using System.IO;
using Lswweb.Model;
using Lswweb.IDAL;
using ExcelLibrary.SpreadSheet;
using QiHe.CodeLib;

namespace Lswweb.Domain
{
    public class ProductStorage
    {
        private static IProductStorage storageDAL = DALFactory.CreateProductStorageDAL();

        #region 查询

        public static ProductStorageInfo GetProductStorage(int id)
        {
            if (id <= 0)
                return null;

            return storageDAL.GetProductStorage(id);
        }

        public static IList<ProductStorageInfo> GetProductStorages(string searchKey, string productName, string brandName, bool? isTop,bool? isHot, int pageIndex, int pageSize, out int totalRecord)
        {
            return storageDAL.GetProductStorages(searchKey, productName, brandName, isTop, isHot, SiteContext.Current.Language, pageIndex, pageSize, out totalRecord);
        }

        #endregion

        #region 更新


        public static void Update(ProductStorageInfo productStorageInfo)
        {
            if (storageDAL.Update(productStorageInfo))
            {
                SiteContext.RenderMessage(ExceptionType.HandleSuccess);
            }
            else
            {
                SiteContext.RenderMessage(ExceptionType.UnknownError);
            }
        }

        public static void UpdateIsHot(int id, bool isHot)
        {
            if (id <= 0)
            {
                SiteContext.RenderMessage(ExceptionType.UnknownError);
                return;
            }

            string url = SiteContext.Current.Context.Request.UrlReferrer.PathAndQuery;
            if (storageDAL.UpdateIsHot(id, isHot))
                SiteContext.RenderMessage(ExceptionType.HandleSuccess, url);
            else
                SiteContext.RenderMessage(ExceptionType.UnknownError);
        }

        public static void UpdateIsTop(int id, bool isTop)
        {
            if (id <= 0)
            {
                SiteContext.RenderMessage(ExceptionType.UnknownError);
                return;
            }

            string url = SiteContext.Current.Context.Request.UrlReferrer.PathAndQuery;
            if (storageDAL.UpdateIsTop(id, isTop))
                SiteContext.RenderMessage(ExceptionType.HandleSuccess, url);
            else
                SiteContext.RenderMessage(ExceptionType.UnknownError);
        }

        #endregion

        #region 添加/删除

        public static void Insert(ProductStorageInfo productStorageInfo)
        {
            if (storageDAL.Insert(productStorageInfo) > 0)
                SiteContext.RenderMessage(ExceptionType.HandleSuccess);
            else
                SiteContext.RenderMessage(ExceptionType.UnknownError);
        }

        public static void Delete(int id)
        {
            string returnUrl = SiteContext.Current.ReferrerUrl;
            ProductStorageInfo info = GetProductStorage(id);
            if (info == null)
            {
                SiteContext.RenderMessage(ExceptionType.UnknownError, returnUrl);
                return;
            }

            ExceptionType type = ExceptionType.UnknownError;


            if (storageDAL.Delete(id))
                type = ExceptionType.HandleSuccess;
            SiteContext.RenderMessage(type, returnUrl);
        }

        #endregion

        #region ImportExcel

        public static void ImportExcel(string excelFilePath)
        {
            FileInfo excelFile = new FileInfo(excelFilePath);
            if (excelFile.Exists)
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    Workbook book = Workbook.Open(excelFile.FullName);

                    foreach (Worksheet sheet in book.Worksheets)
                    {
                        for (int i = 1; i < sheet.Cells.LastRowIndex; i++)
                        {
                            ProductStorageInfo storage = new ProductStorageInfo();

                            storage.Model = GetExcelCellValue<string>(sheet,i,0);
                            storage.ProductName = GetExcelCellValue<string>(sheet, i, 1);
                            storage.BrandName = GetExcelCellValue<string>(sheet, i, 2);
                            storage.BatchNo = GetExcelCellValue<string>(sheet, i, 3);
                            try
                            {
                                storage.Quantity = GetExcelCellValue<int>(sheet, i, 4);
                            }
                            catch (FormatException)
                            {
                                storage.Quantity = 0;
                            }
                            storage.Remark = GetExcelCellValue<string>(sheet, i, 5);

                            storage.Ver = SiteContext.Current.Language;

                            storageDAL.Insert(storage);
                        }
                    }

                    scope.Complete();
                }
            }
        }

        private static TReturn GetExcelCellValue<TReturn>(Worksheet shell,int rowIndex,int collIndex)
        {
            try
            {
                return (TReturn)Convert.ChangeType(shell.Cells[rowIndex, collIndex].Value, typeof(TReturn));
            }
            catch(InvalidCastException)
            {
                return default(TReturn);
            }
        }

        #endregion

        public static string BuilderHtmlTableByCart(IShoppingCart cart)
        {
            if (cart.Items.Count == 0)
                return string.Empty;

            StringBuilder htmlTable = new StringBuilder();
            htmlTable.Append("<table style='text-align:center;'>");
            htmlTable.Append("<tr style='font-weight:bold;'><td>型号</td><td>封装</td><td>品牌</td><td>批号</td><td>数量</td><td>交易说明</td></tr>");
            foreach (IShoppingCartItem cartItem in cart.Items)
            {
                string[] result = cartItem.ProductName.Split('|');
                htmlTable.Append(
                    string.Format(
                    "<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td></tr>", 
                    result[0], 
                    result[1], 
                    result[2], 
                    result[3], 
                    cartItem.Quantity,
                    result[4]));
            }
            htmlTable.Append("</table>");

            return htmlTable.ToString();
        }

        public static void AddToCart(int productStorageId,string model,string produtName,string brandName,string batchNo, int quantity,string remark)
        {
            ShoppingCartItem cartItem = new ShoppingCartItem(
                productStorageId,
                string.Format("{0}|{1}|{2}|{3}|{4}", model, produtName, brandName, batchNo,remark),
                string.Empty,
                0,
                0,
                quantity);

            ShoppingCartFactory.GetShoppingCart().Add(cartItem);
        }
        public static void AddToCart(ProductStorageInfo storage, int quantity)
        {
            if (storage == null)
                return;

            AddToCart(storage.Id, storage.Model, storage.ProductName, storage.BrandName, storage.BatchNo,quantity,storage.Remark);
        }
    }
}
